package org.gordonframework.site.forms.elements {
	import org.gordonframework.core.collection.GItem;	
	import org.gordonframework.site.forms.elements.skins.GElementSkinFactory;	
	import org.gordonframework.site.forms.elements.skins.GElementSkin;
	import org.gordonframework.site.views.GView;		

	/**
	 * @author eriarv
	 */
	public class GElement extends GView implements GItem {

		public static const TYPE : String = "InputElement";
		
		protected var _type : String;
		protected var _id : String;
		protected var _value : String;
		protected var _mandatory : Boolean;
		protected var _text : String;
		protected var skin : GElementSkin;
		protected var _tabIndexable : Boolean;

		public function GElement( 
			type : String, 
			id : String,
			value : String = "",
			mandatory : Boolean = false,
			text : String = "",
			skinClass : Class = null 
		) {
			super();
			_type = type;
			_id = id;
			_value = value;
			_mandatory = mandatory;
			_text = text;
			
			if ( skinClass == null ) {
				skinClass = GElementSkinFactory.getInstance().getSkinClassForType(type);
			}
			skin = new skinClass();
			addChild( skin );
			
			updateSkin();
		}
		
		protected function parseElementXML( xml : XML ) : void {
			_id = xml.@id;
			_type = xml.@type;
			_value = xml.@value;
			_mandatory = String( xml.@mandatory ).toLowerCase( ) == "true";
			_text = xml.@text;
		}
		
		public function get isValid() : Boolean {
			return true;
		}

		public function updateInputErrorStatus() : void {
			skin.valid = isValid;
		}
		
		public function get valueXMLString() : String {
			return '<element id="' + id + '" value="' + replaceEntities( value ) + '"></element>';
		}

		private function replaceEntities( source : String ) : String {
			var result : String = source;
			
			var entities : Array = [["<", "&lt;"],
				[">", "&gt;"],
				["&", "&amp;"]];
			for ( var i : int = 0 ; i < entities.length ; i++ ) {
				result = result.replace( entities[i][0], entities[i][1] );
			}
				
			return result;
		}

		protected function updateSkin() : void {
			skin.update( this );
		}
		
		public function get id() : String {
			return _id;
		}

		
		public function get type() : String {
			return _type;
		}
		
		public function get value() : String {
			return _value;
		}
		
		public function get mandatory() : Boolean {
			return _mandatory;
		}
		
		public function get text() : String {
			return _text;
		}
		
		public function set text(text : String) : void {
			_text = text;
		}
		
		public function set value(value : String) : void {
			_value = value;
		}
		
		public override function set tabIndex( value : int ) : void {
			skin.tabIndex = value;
		}
		
		public function get tabIndexable() : Boolean {
			return _tabIndexable;
		}
		
		public function set tabIndexable(tabIndexable : Boolean) : void {
			_tabIndexable = tabIndexable;
		}
	}
}
